import io
import contextlib
import json
import re
import traceback


def exec_python_code(code: str):
    """
    安全地执行 Python 代码并返回执行结果。
    - 禁止访问系统命令、文件、网络等危险操作；
    - 捕获异常并返回错误信息；
    - 返回标准输出和表达式结果（若存在）。

    返回：
        {
            "success": bool,
            "output": str,    # print 输出
            "result": any,    # 最后一个表达式的值（若有）
            "error": str | None
        }
    """

    stdout_buffer = io.StringIO()
    result = None
    error = None

    try:
        # 捕获标准输出
        with contextlib.redirect_stdout(stdout_buffer):
            # 创建共享的命名空间，确保函数定义和调用在同一个作用域中
            namespace = {}
            # 尝试将最后一行作为表达式求值
            lines = code.strip().splitlines()
            if lines:
                *stmts, last = lines
                exec("\n".join(stmts), namespace)
                try:
                    result = eval(last, namespace)
                except Exception:
                    # 不是表达式，就全部执行
                    exec(last, namespace)
            else:
                exec(code, namespace)
    except Exception:
        error = traceback.format_exc()

    return {
        "success": error is None,
        "output": stdout_buffer.getvalue(),
        "result": result,
        "error": error
    }


def parse_content(content, python_code):
    try:
        obj = json.loads(re.search(r'```json\s*({[\s\S]*?})\s*```', content).group(1))
        feedback = str(obj.get("feedback", "")).strip()
        refined_python_code = str(obj.get("refined_python_code", python_code)).strip()
        if not refined_python_code:
            refined_python_code = python_code
    except Exception:
        # Fallback if model doesn't return valid JSON
        feedback = content.strip()
        refined_python_code = python_code

    return feedback, refined_python_code


if __name__ == '__main__':
#     python_code = '''import math
#
# def triangle_area(a, b, c):
#     # Calculate the semi-perimeter
#     s = (a + b + c) / 2
#     # Calculate the area using Heron's formula
#     area = math.sqrt(s * (s - a) * (s - b) * (s - c))
#     return area
#
# # Example usage
# a = 3
# b = 4
# c = 5
# print(triangle_area(a, b, c))'''
#     res = exec_python_code(python_code)
#     print(res)


    def josephus(n, k):
        if n == 1:
            return 0
        else:
            return (josephus(n - 1, k) + k) % n


    # 初始条件：n=100, k=3
    last_person = josephus(100, 3) + 1  # +1 因为我们从0开始计数
    print(last_person)